package com.xyy.controller;

import com.xyy.common.PageResult;
import com.xyy.common.Result;
import com.xyy.dto.DoctorQueryDTO;
import com.xyy.entity.Admin;
import com.xyy.entity.Doctor;

import com.xyy.service.AdminService;
import com.xyy.service.DoctorService;
import com.xyy.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@Validated
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private DoctorService doctorService;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody Admin admin) {
        try {
            Admin existingAdmin = adminService.login(admin.getUsername(), admin.getPassword());
            
            // 生成JWT token
            String token = jwtUtil.generateAdminToken(existingAdmin.getUsername(), existingAdmin.getId());
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("admin", existingAdmin);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("管理员登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 创建管理员
     */
    @PostMapping("/create")
    public Result<Void> createAdmin(@Valid @RequestBody Admin createDTO) {
        try {
            adminService.createAdmin(createDTO);
            return Result.success();
        } catch (Exception e) {
            log.error("创建管理员失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新管理员信息
     */
    @PutMapping("/update")
    public Result<Void> updateAdmin(@Valid @RequestBody Admin admin) {
        try {
            adminService.updateAdmin(admin);
            return Result.success();
        } catch (Exception e) {
            log.error("更新管理员失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 软删除管理员
     */
    @DeleteMapping("/delete/{adminId}")
    public Result<Void> deleteAdmin(@PathVariable Long adminId) {
        try {
            adminService.deleteAdmin(adminId);
            return Result.success();
        } catch (Exception e) {
            log.error("删除管理员失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量软删除管理员
     */
    @DeleteMapping("/batch-delete")
    public Result<Void> batchDeleteAdmin(@RequestBody List<Long> adminIds) {
        try {
            adminService.batchDeleteAdmin(adminIds);
            return Result.success();
        } catch (Exception e) {
            log.error("批量删除管理员失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询管理员
     */
    @PostMapping("/page")
    public Result<PageResult<Admin>> pageQuery(@RequestBody Admin admin,
                                              @RequestParam(defaultValue = "1") Integer current,
                                              @RequestParam(defaultValue = "10") Integer size) {
        try {
            PageResult<Admin> result = adminService.pageQuery(admin, current, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询管理员失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询管理员详情
     */
    @GetMapping("/detail/{adminId}")
    public Result<Admin> getAdminDetail(@PathVariable Long adminId) {
        try {
            Admin admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return Result.error("管理员不存在");
            }
            return Result.success(admin);
        } catch (Exception e) {
            log.error("查询管理员详情失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取管理员列表
     */
    @GetMapping("/list")
    public Result<List<Admin>> getAdminList() {
        try {
            List<Admin> admins = adminService.getAllAdmins();
            return Result.success(admins);
        } catch (Exception e) {
            log.error("获取管理员列表失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 按医院名称查询医生（普通管理员只能查看自己医院的医生）
     */
    @PostMapping("/doctors")
    public Result<PageResult<Doctor>> getDoctorsByHospital(@RequestBody DoctorQueryDTO queryDTO,
                                                          @RequestParam(defaultValue = "1") Integer current,
                                                          @RequestParam(defaultValue = "10") Integer size,
                                                          HttpServletRequest request) {
        try {
            // 从request属性中获取管理员ID（JWT拦截器已验证并设置）
            Long adminId = (Long) request.getAttribute("adminId");
            if (adminId == null) {
                return Result.error("无效的token");
            }
            
            // 获取管理员信息
            Admin admin = adminService.getAdminById(adminId);
            if (admin == null) {
                return Result.error("管理员不存在");
            }
            
            // 如果是普通管理员，只能查看自己医院的医生
            if (admin.getLevel() == 1) {
                queryDTO.setHospitalName(admin.getRealName());
            }
            
            // 查询医生
            PageResult<Doctor> result = doctorService.pageQueryForAdmin(queryDTO, current, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询医生失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

} 